import { useEffect, useState } from 'react';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Loader2, Server, Cpu, HardDrive, MemoryStick, Info, RefreshCw } from 'lucide-react';
import { get } from '@/lib/apiClient';

interface SystemInfo {
  system: {
    system: string;
    node_name: string;
    release: string;
    version: string;
    machine: string;
    processor: string;
  };
  cpu: {
    physical_cores: number;
    logical_cores: number;
    cpu_percent: number;
    cpu_freq: {
      current: number;
      min: number;
      max: number;
    } | null;
  };
  memory: {
    total: number;
    available: number;
    used: number;
    percent: number;
  };
  disk: {
    total: number;
    used: number;
    free: number;
    percent: number;
  };
  python: {
    version: string;
    implementation: string;
  };
  app: {
    name: string;
    version: string;
    description: string;
    uptime: string;
  };
}

interface AppInfo {
  name: string;
  version: string;
  description: string;
  features: string[];
  tech_stack: {
    frontend: string[];
    backend: string[];
  };
}

export default function About() {
  const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
  const [appInfo, setAppInfo] = useState<AppInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadData = async () => {
    try {
      setLoading(true);
      setError(null);

      // 获取系统信息
      const systemResponse = await get<{ success: boolean; data: SystemInfo }>('/about/system-info');
      if (systemResponse.success) {
        setSystemInfo(systemResponse.data);
      }

      // 获取应用信息
      const appResponse = await get<{ success: boolean; data: AppInfo }>('/about/app-info');
      if (appResponse.success) {
        setAppInfo(appResponse.data);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载数据失败');
      console.error('Failed to load about data:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  const formatBytes = (bytes: number): string => {
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    if (bytes === 0) return '0 B';
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center h-96 gap-4">
        <p className="text-destructive">{error}</p>
        <Button onClick={loadData}>重试</Button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">关于 Feng Admin</h1>
          <p className="text-muted-foreground mt-2">系统信息与应用详情</p>
        </div>
        <Button onClick={loadData} variant="outline" size="sm">
          <RefreshCw className="h-4 w-4 mr-2" />
          刷新
        </Button>
      </div>

      {/* 应用信息 */}
      {appInfo && (
        <Card className="p-6">
          <div className="flex items-center gap-3 mb-4">
            <Info className="h-6 w-6 text-primary" />
            <h2 className="text-2xl font-semibold">应用信息</h2>
          </div>
          
          <div className="space-y-4">
            <div>
              <h3 className="text-lg font-medium mb-2">{appInfo.name}</h3>
              <p className="text-muted-foreground">{appInfo.description}</p>
              <Badge className="mt-2">版本 {appInfo.version}</Badge>
            </div>

            <div>
              <h4 className="font-medium mb-2">核心功能</h4>
              <div className="flex flex-wrap gap-2">
                {appInfo.features.map((feature, index) => (
                  <Badge key={index} variant="secondary">
                    {feature}
                  </Badge>
                ))}
              </div>
            </div>

            <div>
              <h4 className="font-medium mb-2">技术栈</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground mb-2">前端</p>
                  <div className="flex flex-wrap gap-2">
                    {appInfo.tech_stack.frontend.map((tech, index) => (
                      <Badge key={index} variant="outline">
                        {tech}
                      </Badge>
                    ))}
                  </div>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground mb-2">后端</p>
                  <div className="flex flex-wrap gap-2">
                    {appInfo.tech_stack.backend.map((tech, index) => (
                      <Badge key={index} variant="outline">
                        {tech}
                      </Badge>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Card>
      )}

      {/* 系统信息 */}
      {systemInfo && (
        <>
          {/* 系统基本信息 */}
          <Card className="p-6">
            <div className="flex items-center gap-3 mb-4">
              <Server className="h-6 w-6 text-primary" />
              <h2 className="text-2xl font-semibold">系统信息</h2>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <p className="text-sm text-muted-foreground">操作系统</p>
                <p className="font-medium">{systemInfo.system.system} {systemInfo.system.release}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">主机名</p>
                <p className="font-medium">{systemInfo.system.node_name}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">架构</p>
                <p className="font-medium">{systemInfo.system.machine}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">运行时间</p>
                <p className="font-medium">{systemInfo.app.uptime}</p>
              </div>
            </div>
          </Card>

          {/* CPU 信息 */}
          <Card className="p-6">
            <div className="flex items-center gap-3 mb-4">
              <Cpu className="h-6 w-6 text-primary" />
              <h2 className="text-2xl font-semibold">CPU</h2>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <p className="text-sm text-muted-foreground">处理器</p>
                <p className="font-medium">{systemInfo.system.processor}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">核心数</p>
                <p className="font-medium">
                  {systemInfo.cpu.physical_cores} 物理核心 / {systemInfo.cpu.logical_cores} 逻辑核心
                </p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">使用率</p>
                <div className="flex items-center gap-2">
                  <div className="flex-1 bg-secondary rounded-full h-2">
                    <div
                      className="bg-primary h-2 rounded-full transition-all"
                      style={{ width: `${systemInfo.cpu.cpu_percent}%` }}
                    />
                  </div>
                  <span className="font-medium">{systemInfo.cpu.cpu_percent.toFixed(1)}%</span>
                </div>
              </div>
              {systemInfo.cpu.cpu_freq && (
                <div>
                  <p className="text-sm text-muted-foreground">频率</p>
                  <p className="font-medium">
                    {systemInfo.cpu.cpu_freq.current.toFixed(0)} MHz
                  </p>
                </div>
              )}
            </div>
          </Card>

          {/* 内存信息 */}
          <Card className="p-6">
            <div className="flex items-center gap-3 mb-4">
              <MemoryStick className="h-6 w-6 text-primary" />
              <h2 className="text-2xl font-semibold">内存</h2>
            </div>
            
            <div className="space-y-4">
              <div>
                <div className="flex justify-between mb-2">
                  <span className="text-sm text-muted-foreground">使用情况</span>
                  <span className="font-medium">
                    {formatBytes(systemInfo.memory.used)} / {formatBytes(systemInfo.memory.total)}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="flex-1 bg-secondary rounded-full h-2">
                    <div
                      className="bg-primary h-2 rounded-full transition-all"
                      style={{ width: `${systemInfo.memory.percent}%` }}
                    />
                  </div>
                  <span className="font-medium">{systemInfo.memory.percent.toFixed(1)}%</span>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground">已用</p>
                  <p className="font-medium">{formatBytes(systemInfo.memory.used)}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">可用</p>
                  <p className="font-medium">{formatBytes(systemInfo.memory.available)}</p>
                </div>
              </div>
            </div>
          </Card>

          {/* 磁盘信息 */}
          <Card className="p-6">
            <div className="flex items-center gap-3 mb-4">
              <HardDrive className="h-6 w-6 text-primary" />
              <h2 className="text-2xl font-semibold">磁盘</h2>
            </div>
            
            <div className="space-y-4">
              <div>
                <div className="flex justify-between mb-2">
                  <span className="text-sm text-muted-foreground">使用情况</span>
                  <span className="font-medium">
                    {formatBytes(systemInfo.disk.used)} / {formatBytes(systemInfo.disk.total)}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="flex-1 bg-secondary rounded-full h-2">
                    <div
                      className="bg-primary h-2 rounded-full transition-all"
                      style={{ width: `${systemInfo.disk.percent}%` }}
                    />
                  </div>
                  <span className="font-medium">{systemInfo.disk.percent.toFixed(1)}%</span>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground">已用</p>
                  <p className="font-medium">{formatBytes(systemInfo.disk.used)}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">可用</p>
                  <p className="font-medium">{formatBytes(systemInfo.disk.free)}</p>
                </div>
              </div>
            </div>
          </Card>

          {/* Python 环境 */}
          <Card className="p-6">
            <div className="flex items-center gap-3 mb-4">
              <Server className="h-6 w-6 text-primary" />
              <h2 className="text-2xl font-semibold">Python 环境</h2>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <p className="text-sm text-muted-foreground">版本</p>
                <p className="font-medium">{systemInfo.python.version}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">实现</p>
                <p className="font-medium">{systemInfo.python.implementation}</p>
              </div>
            </div>
          </Card>
        </>
      )}
    </div>
  );
}

